<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;
use WePayV3\Cert;


/**
 * @ControllerAnnotation(title="withdrawal")
 */
class Withdrawal extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Withdrawal();
        
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){ 
                    $user = Db::name('user')->where('id',$v['uid'])->field('nickname')->find();
                    if(!empty($user)){
                        $v['nickname'] = $user['nickname'];
                    }else{
                        $v['nickname'] = "";
                    }
                  
                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    
   
    //通过
    public function adopt_url(){
        // $res = $this->newtixian();
        // dump($res);die;
        $post = $this->request->param();
        $flag = Db::name("withdrawal")->where("id",$post["id"])->where("status","in","1,2")->find();
        if(!empty($flag)){
            $this->error('已审核，请重新提交');
        }
        $res = Db::name("withdrawal")->where("id",$post["id"])->where("status",0)->find();
        //审核通过增加已提现佣金 1分销商，2陪玩
        if($res["type"] == 1){
            Db::name("user")->where("id",$res["uid"])->inc("endmoney",$res["money"])->update();
        }elseif($res["type"] == 2){
            Db::name("service_technician")->where("id",$res["service_technician_id"])->inc("yt_blanace",$res["money"])->update();
        }else{
            $this->error('提现类型错误');
        }
        Db::name("withdrawal")->where("id",$post["id"])->update(["status"=>1]);
        $this->success("操作成功");
    }

    /**
    * @NodeAnotation(title="驳回")
    */
    public function reject_url()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post["reason_for_rejection"])){
                $this->error("驳回原因不能为空");
            }
            $flag = Db::name("withdrawal")->where("id",$post["id"])->where("status","in","1,2")->find();
            if(!empty($flag)){
                $this->error('已审核，请重新提交');
            }
            $res = Db::name("withdrawal")->where("id",$post["id"])->where("status",0)->find();
            //审核拒绝给返回佣金 1分销商，2陪玩
            if($res["type"] == 1){
                Db::name("user")->where("id",$res["uid"])->inc("commission",$res["money"])->update();
            }elseif($res["type"] == 2){
                Db::name("service_technician")->where("id",$res["service_technician_id"])->inc("ke_blanace",$res["money"])->update();
            }else{
                $this->error('提现类型错误');
            }
            
            Db::name("withdrawal")->where("id",$post["id"])->update(["status"=>2,"reason"=>$post["reason_for_rejection"]]);
            $this->success('驳回成功', '');
        }
        return $this->fetch();
    }


    //新提现
    public function newtixian(){
            
 
        // 商户号
        $merchantId = '1533318541';
       
        //D:\phpstudy_pro\WWW\peiwan\/cert/apiclient_key.pem
        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyFilePath = 'file://'.root_path() . '/cert/apiclient_key.pem';
        
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
     
        // 「商户API证书」的「证书序列号」
        $merchantCertificateSerial = '5157F09EFDC096DE15EBE81A47057A7232F1B8E1';// 348FD78C5A7D49BCE682626E0A562B6A2B981A7E
        
        // 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
        $platformCertificateFilePath = 'file://'.root_path() . '/cert/apiclient_cert.pem';
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);

        // 从「微信支付平台证书」中获取「证书序列号」
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
       
        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid'      => $merchantId,
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);
        dump($instance);die;
        $partner_trade_no = time() . rand(100, 999);   #订单号
        $amount = 0.01;     #总金额   最小0.3，最大5000，以分为单位，金额*100 0.3 * 100
  
        try {
            $resp = $instance
            ->chain('/v3/transfer/batches')
            ->post([
                'json' => [
                    'appid'        => 'wxe2943a6ef9364385',
                    'mchid'        => '1533318541',
                    'out_trade_no' => $partner_trade_no,
                    'batch_name'  => '测试转账',
                    'batch_remark'   => '测试转账',
                    'total_amount'  => $amount,
                    'total_num'   => 1,
                    'transfer_detail_list'       => [
                        'out_detail_no'    => "x23zy545Bd5436",
                        'transfer_amount' => $amount,
                        'transfer_remark' => '测试用户转账',
                        'openid' => 'oUj-x55oX0gbzuEnWiQDelCaEbFk',
                        'user_name' => '张三'
                    ],
            ]]);
            dump($resp->getBody());die;
        
            // echo $resp->getStatusCode(), PHP_EOL;
            // echo $resp->getBody(), PHP_EOL;
        } catch (\Exception $e) {
            dump($e->getMessage());die;
            // 进行错误处理
            // echo $e->getMessage(), PHP_EOL;
            // if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
            //     $r = $e->getResponse();
            //     echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
            //     echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
            // }
            // echo $e->getTraceAsString(), PHP_EOL;
        }

        // // 发送请求
        // $resp = $instance->chain('v3/certificates')->get(
        //     ['debug' => true] // 调试模式，https://docs.guzzlephp.org/en/stable/request-options.html#debug
        // );
        // echo $resp->getBody(), PHP_EOL;
    }

     
 

     //提现
     public function wx_withdrawal()
     {
         header('content-type:text/html;charset=utf-8');
         $mch_appid = "wxe2943a6ef9364385";   #appid
         $key = "AKIDhEWYKr88s1uXu0qQkna6LKqkhmsd";     #商户key
         $mchid = "1533318541";    #商户号
         $desc = '提现';
         $openid = 'oUj-x55oX0gbzuEnWiQDelCaEbFk';
         $check_name = 'NO_CHECK';     #此参数为不验证真实姓名，如果需要验证真实姓名，请参考微信文档，注意参数排序，否则将报错->签名错误
         #$re_user_name='';        #微信真实姓名
  
         $nonce_str = strtoupper(md5(time()));
         $partner_trade_no = time() . rand(100, 999);   #订单号
         $amount = 0.3 * 100;     #总金额   最小0.3，最大5000，以分为单位，金额*100
         $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
         $www_url = $_SERVER['HTTP_HOST'];
         $stringA = "amount={$amount}&check_name={$check_name}&desc={$desc}&mch_appid={$mch_appid}&mchid={$mchid}&nonce_str={$nonce_str}&openid={$openid}&partner_trade_no={$partner_trade_no}&spbill_create_ip={$spbill_create_ip}";
         $stringSignTemp = $stringA . "&key=" . $key;
         $sign = strtoupper(md5($stringSignTemp));
      
         $postData =
            "<xml>
            <amount>{$amount}</amount>
            <check_name>{$check_name}</check_name>
            <desc>{$desc}</desc>
            <mch_appid>{$mch_appid}</mch_appid>
            <mchid>{$mchid}</mchid>
            <nonce_str>{$nonce_str}</nonce_str>
            <openid>{$openid}</openid>
            <partner_trade_no>{$partner_trade_no}</partner_trade_no>
            <spbill_create_ip>{$spbill_create_ip}</spbill_create_ip>
            <sign>{$sign}</sign>
            </xml>";
         $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
         $res = $this->postCertXmlCurl($url, $postData); #在这里post请求是要带证书，方法如下
       
         //dump($res);die;
         if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
             #执行提现到账后的逻辑
             echo '成功';
         } else {
             $this->error($res['err_code_des']);
         }
     }
  
     function postCertXmlCurl($url, $xml)
     {
  
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//严格校验
         //设置header
         curl_setopt($ch, CURLOPT_HEADER, FALSE);
         //要求结果为字符串且输出到屏幕上
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);//证书检查
         curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
         curl_setopt($ch, CURLOPT_SSLCERT, root_path() . '/cert/apiclient_cert.pem');
         curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
         curl_setopt($ch, CURLOPT_SSLKEY, root_path() . '/cert/apiclient_key.pem');
         curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
         curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        
        // $_SERVER['DOCUMENT_ROOT']
         //post提交方式
         curl_setopt($ch, CURLOPT_POST, TRUE);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
         //运行curl
         $data = curl_exec($ch);
      
        //$error = curl_errno($ch);
     
        $objectxml = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
         
        //dump($objectxml);die;
        return $objectxml;
     }
   



































    
}